<template>
	<view class="graybg">
		<view class="rrcard">
			<view class="box">
				<view class="billItem">
					<view>订单编号： <text>{{order.id}}</text></view>
					<view v-if="orderFrom==0">下单时间： <text>{{dayjs().format('YYYY-MM-DD')}}</text></view>
					<view v-if="orderFrom==1">下单时间： <text>{{order.createTime}}</text></view>
					<view>预订人： <text>{{currUser.userName||order.orderName}}</text></view>
					<view>手机号： <text>{{currUser.phonenumber||order.orderTelno}}</text></view>
				</view>
			</view>
		</view>
		<view class="rrcard">
			<view class="t">已选场地信息</view>
			<view class="box">
				<view class="billItem">
					<view v-if="order.projectName">项目： <text>{{order.projectName}}</text></view>
					<view v-else-if="order.sonList">项目： <text>{{order.sonList[0].projectName}}</text></view>
					<view class="billFoot" style="margin:0">
					</view>
					<view v-if="order.sonList" v-for="(info,index) in order.sonList" :key="info.id">
						{{`明细 ${info.siteName}  ${info.orderDate.substring(5,10)}  (${info.orderTimePeriod.replace(/,/,'-')} )  ${info.orderHour}小时`}}
						<text style="width: auto;">￥{{info.orderAmount}}</text>
					</view>
					<view v-if="!order.sonList">
						{{`明细 ${order.siteName} ${order.orderDate.substring(5,10)}  (${order.orderTimePeriod.replace(/,/,'-')})  ${order.orderHour}小时`}}<text
							style="width: auto;">￥{{order.orderAmount}}</text>
					</view>
					<view></view>
				</view>

			</view>
		</view>
		<view class="rrcard">
			<view class="t">付款信息</view>
			<view class="box">
				<view class="billItem">
					<view>合计：
						<!-- 原价 -->
						<text class="originPrice" v-if="form.payType =='2'">￥{{order.unuseBalancePrice}}</text>
						<!-- 优惠价 useBalancePrice-->
						<text v-if="form.payType =='2'" class="price">￥{{order.useBalancePrice}}</text>
						<text v-if="form.payType =='7'" class="price">￥{{order.unuseBalancePrice}}</text>
					</view>
					<view>备注：
						<input placeholder="给商家留言" v-model="form.remark" type="text" />
					</view>
				</view>
			</view>
		</view>

		<view class="rrcard">
			<view class="t">支付方式</view>
			<view class="whitebg">
				<radio-group @change="payChange">
					<label class="uni-list-cell uni-list-cell-pd">
						<view class="littleimgBox">
							<image class="littleimg" src="@/static/zf01.png"></image>微信支付
						</view>
						<view>
							<radio checked="checked" value="7" />
						</view>
					</label>
					<label class="uni-list-cell uni-list-cell-pd">
						<view class="littleimgBox">
							<image class="littleimg" src="@/static/zf02.png"></image>会员卡支付(余额：￥{{myBalance}})
						</view>
						<view>
							<radio checked="checked" value="2" />
						</view>
					</label>
				</radio-group>
			</view>
		</view>
		<view class="payBtnBox" v-if="orderFrom==0">
			<view class="cancelBtn" @click="payCancel">取消订单</view>
			<view class="payBtn" @click="pay(form.payType)">立即支付
				<uni-countdown style="display: inline-block;" color="#fff" splitorColor="#fff" @timeup="timeup"
					:show-day="false" :show-hour="false" :minute="15" :second="0"></uni-countdown>
			</view>
		</view>
		<view class="payBtnBox" v-else>
			<view class="payBtn" style="width: 100%;" @click="pay(form.payType)">立即支付
				<uni-countdown style="display: inline-block;" color="#fff" splitorColor="#fff" @timeup="timeup"
					:show-day="false" :show-hour="false" :start="countdown.start" :minute="countdown.minute"
					:second="countdown.second"></uni-countdown>
			</view>
		</view>

		<uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog type="info" cancelText="取消" confirmText="确定" content="是否确认支付？" @confirm="dialogConfirm" 
				@close="dialogClose"></uni-popup-dialog>
		</uni-popup>

		<uni-popup ref="alertPayOk" type="dialog">
			<uni-popup-dialog type="success" confirmText="查看订单详情" content="支付成功" @confirm="goBillDetail"  @close="goBillDetail">
			</uni-popup-dialog>
		</uni-popup>
		<uni-popup ref="alertPayWrong" type="dialog">
			<uni-popup-dialog type="error" confirmText="查看订单详情" content="支付失败" @confirm="goBillDetail" @close="goBillDetail">
			</uni-popup-dialog>
		</uni-popup>

	</view>

</template>

<script setup>
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import * as api from '@/common/api.js';
	import _ from 'lodash'
	import {
		ref,
		getCurrentInstance
	} from 'vue';
	import dayjs from 'dayjs'
	import {
		getCurrUser
	} from '../../common/login';


	const {
		proxy
	} = getCurrentInstance()

	const vTypeImg = ref('/static/v1.png');
	const items = ref(['消费记录', '充值记录']);
	const current = ref(0);
	const isPay = ref(false);
	const lockPay = ref(false);
	const isClick = ref(false);
	const alertDialog = ref(null);
	const alertPayOk = ref(null);
	const alertPayWrong = ref(null);
	const currUser = ref({});
	const orderId = ref('');
	const order = ref({});
	const orderFrom = ref(0);
	const orderInfo = ref([]);
	const myBalance = ref(0);
	const form = ref({
		payType: '2'
	});
	const countdown = ref({
		start: false,
		minute: 0,
		second: 0
	})

	onLoad((option) => {
		uni.showLoading({
			title: '加载中'
		});
		if (option.id) {
			orderFrom.value = 1
			api.getMaItemById(option.id).then(res => {
				uni.hideLoading();
				order.value = res.data
				form.value.orderId = option.id
				orderId.value = option.id
				form.value.orderAmount = res.data.useBalancePrice

				let leftTime = dayjs(res.data.createTime).add(15, 'minute').valueOf() - dayjs().valueOf()
				if (leftTime > 0) {
					countdown.value = {
						start: true,
						minute: Math.floor(leftTime / 1000 / 60),
						second: Math.ceil(leftTime / 1000) % 60
					}
				} else {
					countdown.value = {
						start: true
					}
					timeup()
				}
			})
		} else {
			const eventChannel = proxy.getOpenerEventChannel()
			eventChannel.on('acceptDataFromOpenerPage', (data) => {
				// console.log(data)
				orderInfo.value = data.orderInfo
				orderId.value =  data.order.id
				api.getMaItemById(orderId.value).then(res => {
					uni.hideLoading();
					order.value = res.data
					form.value.orderAmount = res.data.useBalancePrice
				})

				eventChannel.emit('acceptDataFromOpenedPage');

				countdown.value = {
					start: true
				}
			})
		}

		currUser.value = uni.getStorageSync('currUser')

		api.getMyBalance().then((res) => {
			myBalance.value = res.data
		})
	})

	function payChange(evt) {
		form.value.payType = evt.detail.value
	}

	function pay(n) {
		if(lockPay.value == true){
			return
		}else{
			lockPay.value = true
		}
		if (n == '2'&&(parseFloat(myBalance.value) < parseFloat(order.value.useBalancePrice))) {
			uni.showToast({
				title: '余额不足，无法支付',
				icon: 'none',
				duration: 2000
			})
			lockPay.value = false
		} else {
			alertDialog.value.open()
		}
	}

	let timeHandle = null;

	function dialogConfirm() {
		// console.log(isClick.value)
		if(isClick.value == true){
			return
		} else {
			isClick.value = true
			uni.showLoading({
				title: '支付中...'
			});
			goPayForOrder()
		}
	}

	function goPayForOrder() {
		if (form.value.payType != '2') {
			form.value.orderAmount = order.value.unuseBalancePrice
		}
		api.payForOrder(orderId.value, form.value)
			.then((res) => {
				isClick.value = false
				if (res.data.weixinData) {
					// console.log('weipay')
					wePay(res.data.weixinData)
				} else {
					alertPayOk.value.open()
					subscribe()
					lockPay.value = true
				}
			}).catch(() => {
				alertPayWrong.value.open()
			}).finally(() => {
				uni.hideLoading()
				// timeHandle = setTimeout(() => {
				// 	goBillDetail()
				// }, 3000)
			})
	}


	function wePay(configdata) {
		// console.log(configdata)
		// 微信支付
		uni.requestPayment({
			"provider": "wxpay",
			"appId": configdata.appId,
			"nonceStr": configdata.nonceStr,
			"package": configdata.packageValue, // 随机字符串
			"timeStamp": configdata.timeStamp, // 时间戳（单位：秒）
			"signType": configdata.signType, // 签名，这里用的 MD5/RSA 签名
			"paySign": configdata.paySign,
			success(res) {
				alertPayOk.value.open()
				subscribe()
				api.maPayConfirm({
					orderId:orderId.value,
					successFlag:true
				}).then((res)=>{
					lockPay.value = false
				})
			},
			fail(e) {
				uni.showToast({
					title: '支付取消',
					icon: 'none',
					duration: 2000
				})
				api.maPayConfirm({
					orderId:orderId.value,
					successFlag:false
				}).then((res)=>{
					lockPay.value = false
				})

			}
		})
	}

	function payCancel() {
		uni.showModal({
			title: '提示',
			content: '确定取消订单吗',
			success: function(res) {
				if (res.confirm) {
					const eventChannel = proxy.getOpenerEventChannel()
					api.cancelOrder(orderId.value).then((res) => {
						eventChannel.emit('acceptDataFromOpenedPage');
						uni.navigateBack()
					})
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}

	function dialogClose() {
		alertDialog.value.close()
		lockPay.value = false
	}

	function goBillDetail() {
		if (timeHandle) {
			clearTimeout(timeHandle)
		}
		uni.redirectTo({
			url: `/pages/usercenter/billsDetail?id=${orderId.value}`
		})
	}

	function timeup() {
		if (countdown.value.start) {
			// 自动取消订单
			uni.showModal({
				title: '提示',
				content: '订单支付已超时',
				showCancel: false,
				success: function(res) {
					if (res.confirm) {
						api.cancelOrder(orderId.value).then((res) => {
							uni.navigateBack()
						})
					}
				}
			})
		}
	}

	// 订阅
	function subscribe() {
		// 场馆预订成功通知 订场取消提醒 订单退款通知
		uni.requestSubscribeMessage({
			tmplIds: ['p7_a1SGyGvJeOdwx_GKl6UlrWiWpNnejUArbnEPf-k4'],
			success: (res) => {
				console.log('success:', res)
			}
		})
	}

</script>

<style lang="scss" scoped>
	.billItem {
		width: auto;

		.uni-input {
			padding: 15rpx 0;
			color: #000;
		}

		.trInput {
			text-align: right;
			float: right;
		}
	}

	.rrcard .box {
		padding: 0 0 1px;
		margin: 20rpx 0 0;
	}

	.graybg {
		background: #f7f8fa;
		height: 100vh;
		width: 100vw;
		overflow: auto;
	}

	.whitebg {
		background: #fff;
		margin-top: 15rpx;
		border-radius: 20rpx;
		margin-bottom: 180rpx;
	}

	.payBtnBox {
		width: 750rpx;
		line-height: 90rpx;
		position: fixed;
		bottom: 0;
		display: flex;
		height: 120rpx;
	}

	.cancelBtn {
		background: #fff;
		font-size: 28rpx;
		color: #999;
		text-align: center;
		width: 40%;
	}

	.payBtn {
		background: #FF8124;
		text-align: center;
		color: #FFFFFF;
		width: 60%;
		font-size: 36rpx;
	}

	.uni-list-cell::after {
		display: none;
	}

	.littleimgBox {
		display: flex;
		align-items: center;
	}

	.littleimg {
		width: 50rpx;
		height: 50rpx;
		margin-right: 15rpx;
	}

	.billItem .price {
		font-weight: bold;
		font-size: 45rpx;
		color: #ff8124;
	}

	.originPrice {
		line-height: 70rpx;
		margin: 0 0 0 6rpx;
		color: #999;
		text-decoration: line-through;
	}
</style>
